var hostAddr = 'your host addr';   /* udp server host address */
var hostPort = 'your port';    /* udp server host port */

function ArrayToString(fileData) {
    var dataString = "";
    for (var i = 0; i < fileData.length; i++) {
        dataString += String.fromCharCode(fileData[i]);
    }

    return dataString;
}

var udp = require('udp');
var network = require('network');
var net = network.openNetWorkClient();

function createUdpClient() {
    var udpSocket = udp.createSocket();

    udpSocket.bind(10240);
    if (!udpSocket.localPort || typeof udpSocket.localPort !== 'number') {
        throw new Error("udp: [failed] udp localPort");
    }

    udpSocket.on('message', function (message, rinfo) {
        if (!message) {
            throw new Error("udp: [failed] udp receive message");
        }
        if (!rinfo || !rinfo.host || !rinfo.port) {
            throw new Error("udp: [failed] udp receive rinfo");
        }
        console.log('udp: [debug] remote[' + rinfo.host + ': ' + rinfo.port + '] on message: ' + ArrayToString(message));
    });

    // 测试socket异常
    udpSocket.on('error', function (err) {
        console.log('udp error ', err);
        throw new Error("udp: [failed] udp on error");
    });

    // 测试发送数据
    udpSocket.send({
        address: hostAddr,
        port: hostPort,
        message: "this is amp test!",
        success: function () {
            console.log("udp: [debug] send success");
        },
        fail: function () {
            console.log("udp: send fail");
            throw new Error("udp: [failed] udp send fail");
        }
    });

    console.log('udp: [success] udp.localPort');
}

var status = net.getStatus();
console.log('net status is: ' + status);

if (status == 'connect') {
    createUdpClient();
} else {
    net.on('connect', function () {
        createUdpClient();
    });
}